package redisdb

import (
	"github.com/go-redis/redis"
	"math"
	"strconv"
	"time"
)

var RedisClient *redis.Client

func init() {
	instanceClient := redis.NewClient(&redis.Options{
		Addr:     "127.0.0.1:6379",
		//Password: "12346", // 设置密码
		DB:       1,
	})
	_, err := instanceClient.Ping().Result()
	if err != nil {
		panic(err)
	}
	RedisClient = instanceClient
}

func GetCacheById(id string) (string, error) {
	val, err := RedisClient.Get(id).Result()
	switch {
	case err == redis.Nil:
		err = nil
	case err != nil:
		return val, err
	}
	return val, err
}

func SetCacheById(id string, recordNum int, timeout int) (string, error) {
	val, err := RedisClient.Set(id, recordNum, time.Duration(timeout)*time.Second).Result()
	return val, err
}

func DeleteCacheByIds(testsuitIds []string) error {
	_, err := RedisClient.Del(testsuitIds...).Result()
	return err
}

func StatisticsMatchIncr() error {
	return BaseIncr(GetStatisticsMatchKey())
}

func FailureMatchIncr() error {
	return BaseIncr(GetfailureMatchKey())
}

func BaseIncr(key string) error {
	val, err := RedisClient.Exists(key).Result()
	if val == 0 {
		_, err = RedisClient.Incr(key).Result()
		if err != nil {
			return err
		}
		_, err = RedisClient.Expire(key, 60*60*24*time.Second).Result()
		if err != nil {
			return err
		}
	} else {
		val, err = RedisClient.Incr(key).Result()
		if err != nil {
			return err
		}
	}
	return nil
}

func GetStatisticsMatchPercentage () (float64, error) {
	val, err := RedisClient.Exists(GetStatisticsMatchKey()).Result()
	if err != nil {
		return 0, err
	}
	if val==0{
		return 0, nil
	} else {
		val2, err := RedisClient.Exists(GetfailureMatchKey()).Result()
		if err != nil {
			return 0, err
		}
		if val2 == 0 {
			return 0, nil
		} else {
			sucessCount, err := RedisClient.Get(GetStatisticsMatchKey()).Result()
			if err != nil {
				return 0, nil
			}
			failedCount, err := RedisClient.Get(GetfailureMatchKey()).Result()
			if err != nil {
				return 0, nil
			}
			sucessCountF,err := strconv.ParseFloat(sucessCount,64)
			failedCountF,err := strconv.ParseFloat(failedCount,64)
			return Decimal(sucessCountF/(sucessCountF+failedCountF)), nil
		}
	}
}

func Decimal(value float64) float64 {
	return math.Trunc(value*1e2+0.5) * 1e-2
}

func GetStatisticsMatchKey () string {
	return time.Unix(time.Now().Unix(), 0).Format("2006-01-02") + "_StatisticsMatch"
}

func GetfailureMatchKey () string {
	return time.Unix(time.Now().Unix(), 0).Format("2006-01-02") + "_failureMatch"
}